package com.yzt.zhuju.file;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.yzt.zhuju.event.BaseBusEvent;
import com.yzt.zhuju.event.RxBus;
import com.yzt.p_base.utils.TLogManager;
import com.yzt.p_base.utils.ZipUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   :
 */
public class FileDownloadManager {

    private final String TAG = FileDownloadManager.class.getSimpleName();

    private static final String TAG_MODULE = "ChatRoom";

    private static FileDownloadManager mInstance;

    protected FileDownloadManager() {

    }

    public static FileDownloadManager getInstance() {
        if (mInstance == null) {
            synchronized (FileDownloadManager.class) {
                if (mInstance == null) {
                    mInstance = new FileDownloadManager();
                }
            }
        }
        return mInstance;
    }

    public void init(Context mContext) {
        FileDownloader.setup(mContext);
    }

    public void loadFile() {
        // 以相同的listener作为target，将不同的下载任务绑定起来
        final FileDownloadListener parallelTarget = createListener();
        final List<BaseDownloadTask> taskList = new ArrayList<>();
        int i = 0;
        for (String url : FileUrlsConstant.DOWN_FILE) {
            String savePath = FileUrlsConstant.SAVE_PATH.get(url);
            if (savePath == null) {
                savePath = FileManager.getDefaultPath();
            }
            taskList.add(FileDownloader.getImpl().create(url)
                    .setTag(String.valueOf(++i)).setPath(savePath, true));
        }
        new FileDownloadQueueSet(parallelTarget)
                .setCallbackProgressTimes(1)
                .downloadTogether(taskList)
                .start();
    }

    public int loadSingleFile4Zip(String url, String mSinglePath, BaseBusEvent event) {
        return loadSingleFile(url, mSinglePath, new FileDownloadSampleListener() {
            @Override
            protected void completed(BaseDownloadTask task) {
                FileDownloadManager.unZipFile(task.getTargetFilePath(), mSinglePath);

                if (event != null) {
                    RxBus.getDefault().post(event);
                }
            }
        });
    }

    public int loadSingleFile4Zip(String url, BaseBusEvent event) {
        return loadSingleFile4Zip(url, FileManager.getDefaultPath(), event);
    }

    public int loadSingleFile(String url, String mSinglePath, FileDownloadListener listener) {
        BaseDownloadTask singleTask;
        singleTask = FileDownloader.getImpl().create(url)
                .setPath(mSinglePath, true)
                .setCallbackProgressTimes(300)
                .setMinIntervalUpdateSpeed(400)
                .setListener(listener);

        return singleTask.start();
    }

    private FileDownloadListener createListener() {

        return new FileDownloadListener() {

            @Override
            protected boolean isInvalid() {
                return false;
            }

            @Override
            protected void pending(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
                Log.e("", String.format("IreneBond [pending] id[%d] %d/%d", task.getId(), soFarBytes, totalBytes));
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                Log.e("", String.format("IreneBond [connected] id[%d] %s %B %d/%d", task.getId(), etag, isContinue, soFarBytes, totalBytes));
            }

            @Override
            protected void progress(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
                Log.e("", String.format("IreneBond [progress] id[%d] %d/%d", task.getId(), soFarBytes, totalBytes));
            }

            @Override
            protected void blockComplete(final BaseDownloadTask task) {
                Log.e("", String.format("IreneBond [blockComplete] id[%d]", task.getId()));
            }

            @Override
            protected void retry(BaseDownloadTask task, Throwable ex, int retryingTimes, int soFarBytes) {
                super.retry(task, ex, retryingTimes, soFarBytes);
                Log.e("", String.format("IreneBond [retry] id[%d] %s %d %d",
                        task.getId(), ex, retryingTimes, soFarBytes));
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                Log.e("", String.format("IreneBond [completed] id[%d] oldFile[%B]",
                        task.getId(),
                        task.isReusedOldFile()));
                Log.e("", String.format("IreneBond ---------------------------------- %s", task.getTag()));
                Log.e("", "IreneBond savaPath: " + task.getTargetFilePath());
                FileDownloadManager.unZipFile(task.getTargetFilePath());
                TLogManager.loge(TAG_MODULE, TAG, "FileDownloadListener - completed - ");
            }

            @Override
            protected void paused(final BaseDownloadTask task, final int soFarBytes, final int totalBytes) {
                Log.e("", String.format("IreneBond [paused] id[%d] %d/%d", task.getId(), soFarBytes, totalBytes));
                Log.e("", String.format("IreneBond ############################## %s", task.getTag()));
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                Log.e("", String.format("IreneBond !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! %s", task.getTag()));
                TLogManager.loge(TAG_MODULE, TAG, "FileDownloadListener - error - " + e.getMessage());
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                Log.e("", String.format("IreneBond [warn] id[%d]", task.getId()));
                Log.e("", String.format("IreneBond ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ %s", task.getTag()));
            }
        };
    }

    public static void unZipFile(String filePath) {
        FileDownloadManager.unZipFile(filePath, FileManager.getDefaultPath());
    }

    public static void unZipFile(String filePath, String folderPath) {
        FileDownloadManager.unZipFile(filePath, folderPath, null);
    }

    /**
     * 解压到指定目录
     *
     * @param filePath   要解压的文件
     * @param folderPath 要解压的目录
     */
    public static void unZipFile(String filePath, String folderPath, ZipUtils.OnZipCompleteListener listener) {

        if (!TextUtils.isEmpty(filePath) && filePath.endsWith(".zip")) {
            File mFile = new File(filePath.replace(".zip", ""));
            if (mFile.exists()) {
                Log.e("", "IreneBond 已经存在");
            } else {
                Log.e("", "IreneBond 开始解压");
                ZipUtils.upZipFile(new File(filePath), folderPath, listener);
            }
        }
    }
}
